package com.springcloud.sc.ucpv5.client.application.message.connect;


import com.proto.uuos_sdk_pb;
import com.sun.jna.Callback;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class UcpUserManOamSdk {
	private static final Logger logger = LoggerFactory.getLogger(UcpUserManOamSdk.class);
	private static UcpUserManOamSdk instance;

	private UcpUserManOamSdk() {

	}

	public static synchronized UcpUserManOamSdk getInstance() {
		if (instance == null) {
			System.setProperty("jna.encoding", "GBK");
			instance = new UcpUserManOamSdk();
			instance.init();
		}
		return instance;
	}

	public static String TAG = "UcpUserManOamSdk-java";

	public UcpUserManOamSdkApi INSTANCE = null;
	public interface UcpUserManOamSdkApi extends Library {

//		UcpUserManOamSdkApi INSTANCE = null;

		int uuos_client_init(ClientSdkApiCB cb);

		void uuos_client_connect(String user_name, String ip, int port, String name);

		void uuos_client_disconnect(String user_name);

		boolean uuos_client_send_pack(String user_name, byte[] data, int size);
	}

	public interface OnClientSdkListener {
		void onNotify(uuos_sdk_pb.MsgHeader msg);
	}

	private static OnClientSdkListener cb_ = null;
	public final static ClientSdkApiCB api_cb_ = new ClientSdkApiCB() {
		protected void finalize() {
			;
		}

		public int callback(String user_name, Pointer data, int size) {
			if (null == cb_)
				return -1;

			// logger.info("UcpUserManOamSdk 收到回调, 长度:" + size);

			byte[] contents = data.getByteArray(0, size);

			uuos_sdk_pb.MsgHeader pb_msg;
			try {
				pb_msg = uuos_sdk_pb.MsgHeader.parseFrom(contents);
//				 logger.info("UcpUserManOamSdk 收到回调, 命令字:" + pb_msg.getCmdID());

				try {
//					 System.out.println(Thread.currentThread().getName() + "--" + Thread.currentThread().getId());
				} catch (Exception e) {

				}
//		    if (pb_msg.getCmdID() != 2106 && pb_msg.getCmdID() != 2111) {
//						logger.info("返回回调数据callback:" + pb_msg.getCmdID());
//		    }
				cb_.onNotify(pb_msg);
			} catch (com.google.protobuf.InvalidProtocolBufferException e) {
				e.printStackTrace();
				return -1;
			}
			return 0;
		}
	};

	private void init() {
		// api_cb_ = new ClientSdkApiCB() {
		// protected void finalize() {
		// ;
		// }
		//
		// public int callback(String user_name, Pointer data, int size) {
		// if (null == cb_)
		// return -1;
		//
		// // logger.info("UcpUserManOamSdk 收到回调, 长度:" + size);
		//
		// byte[] contents = data.getByteArray(0, size);
		//
		// uuos_sdk_pb.MsgHeader pb_msg;
		// try {
		// pb_msg = uuos_sdk_pb.MsgHeader.parseFrom(contents);
		// // logger.info("UcpUserManOamSdk 收到回调, 命令字:" +
		// // pb_msg.getCmdID());
		//
		// if (pb_msg.getCmdID() != 2106 && pb_msg.getCmdID() != 2111) {
		// logger.info("返回回调数据callback:" + pb_msg.getCmdID());
		// cb_.onNotify(pb_msg);
		// } else {
		// ;
		// }
		// } catch (com.google.protobuf.InvalidProtocolBufferException e) {
		// e.printStackTrace();
		// return -1;
		// }
		// return 0;
		// }
		// };

//		String path = loadNative("ucp_userman_oam_sdk");
		INSTANCE = (UcpUserManOamSdkApi) Native.loadLibrary( "ucp_userman_oam_sdk" , UcpUserManOamSdkApi.class);
		INSTANCE.uuos_client_init(api_cb_);
		return;
	}

	private synchronized static String loadNative(String nativeName) {
		String systemType = System.getProperty("os.name");
		String fileExt = (systemType.toLowerCase().indexOf("win") != -1) ? ".dll" : ".so";
		File path = new File(".");
		//将所有动态链接库dll/so文件都放在一个临时文件夹下，然后进行加载
		//这是应为项目为可执行jar文件的时候不能很方便的扫描里面文件
		//此目录放置在与项目同目录下的natives文件夹下
		String sysUserTempDir = path.getAbsoluteFile().getParent() + File.separator + "dll";
		System.out.println("->>native lib临时存放目录 : " + sysUserTempDir);
		String fileName = nativeName + fileExt;
		InputStream in = null;
		BufferedInputStream reader = null;
		FileOutputStream writer = null;
		File tempFile = new File(sysUserTempDir + File.separator + fileName);
		if(!tempFile.getParentFile().exists())
			tempFile.getParentFile().mkdirs() ;
		if (tempFile.exists()) {
			tempFile.delete();
		}
		try {
			//读取文件形成输入流
			in = TcpProBufConnect.class.getResourceAsStream("/dll/" + fileName);
			if (in == null)
				in = TcpProBufConnect.class.getResourceAsStream("dll/" + fileName);
			TcpProBufConnect.class.getResource(fileName);
			reader = new BufferedInputStream(in);
			writer = new FileOutputStream(tempFile);
			byte[] buffer = new byte[1024];
			while (reader.read(buffer) > 0) {
				writer.write(buffer);
				buffer = new byte[1024];
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
				if (writer != null)
					writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.load(tempFile.getPath());
		System.out.println("->> 加载native文件 :" + tempFile + "成功!!");
		return tempFile.getPath();
	}

	private interface ClientSdkApiCB extends Callback {
		public int callback(String user_name, Pointer data, int size);
	}

	// 设置回调
	public void set_cb(OnClientSdkListener cb) {
		cb_ = cb;
	}

	public void connect(String user_name, String ip, int port, String name) {
		try {
			logger.info("UcpUserManOamSdk connect :" + user_name + "-" + ip + "-" + port + name);
			INSTANCE.uuos_client_connect(user_name, ip, port, name);
		} catch (Exception e) {

			logger.info("UcpUserManOamSdk connect 异常:" + user_name + "-" + ip + "-" + port + name, e);
		}
	}

	public void disconnect(String user_name) {
		try {
			logger.info("UcpUserManOamSdk disconnect");

			INSTANCE.uuos_client_disconnect(user_name);
		} catch (Exception e) {
			logger.info("UcpUserManOamSdk disconnect 异常:", e);
		}
	}

	public boolean send_pack(String user_name, uuos_sdk_pb.MsgHeader msg) {
		byte[] data = msg.toByteArray();
		// System.out.println("开始发送包 长度:" + data.length);
		return INSTANCE.uuos_client_send_pack(user_name, data, data.length);
	}
}
